package com.practice.crud.controller;

import com.practice.crud.bean.ajaxUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/ajax.jsp")
public class AjaxController {

    @RequestMapping("/ajax")
    public void ajax(String name, HttpServletResponse response) throws IOException {
        if("admin".equals(name)){
            response.getWriter().print("true");
        }else{
            response.getWriter().print("false");
        }
    }

    @PostMapping("/ajax2")
    @ResponseBody
    public List<ajaxUser> ajax2(){
        List<ajaxUser> list = new ArrayList<>();
        list.add(new ajaxUser("Joker1","sing","undergraduate"));
        list.add(new ajaxUser("Joker2","sing","undergraduate"));
        list.add(new ajaxUser("Joker3","sing","undergraduate"));
        list.add(new ajaxUser("Joker4","sing","undergraduate"));
        return list;
    }

    @RequestMapping("/ajax3")
    @ResponseBody
    public String ajax3(String name, String pwd, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        String msg = "";
        // 模拟数据库存在数据
        if (name!=null){
            if ("admin".equals(name)){
                msg = "OK";
            }else {
                msg = "用户名输入错误";
            }
        }
        if (pwd!=null){
            if ("123456".equals(pwd)){
                msg = "OK";
            }else {
                msg = "密码输入有误";
            }
        }
        return msg;
    }
}
